package life.sweet.community.controller;

import life.sweet.community.dto.AccessTokenDTO;
import life.sweet.community.dto.MayunUser;
import life.sweet.community.mapper.UserMapper;
import life.sweet.community.model.User;
import life.sweet.community.provider.MayunProvider;
import life.sweet.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
@Slf4j
public class AuthorizeController {
    @Autowired
    private MayunProvider mayunProvider;

    @Autowired
    private UserMapper userMapper;

    @Value("${mayun.client.id}")
    private String clientId;

    @Value("${mayun.client.secret}")
    private String clientSecret;

    @Value("${mayun.redirect.uri}")
    private String redirectUri;

    @Autowired
    private UserService userService;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           HttpServletResponse response,
                           HttpServletRequest request){
        AccessTokenDTO dto = new AccessTokenDTO();
        dto.setClient_id(clientId);
        dto.setClient_secret(clientSecret);
        dto.setCode(code);
        dto.setRedirect_uri(redirectUri);
        String accessToken = mayunProvider.getAccessToken(dto);
        MayunUser mayunUser = mayunProvider.getUser(accessToken);
        if(null == mayunUser) {
            log.error("mayunUser is null");
            return "redirect:/";
        }
        String accountId = String.valueOf(mayunUser.getId());
        if(StringUtils.isEmpty(accountId)) {
            return "redirect:/";
        }
        log.info("mayunUser is: {}", mayunUser);
        User user = new User();
        String token = UUID.randomUUID().toString();
        user.setName(mayunUser.getName());
        user.setToken(token);
        user.setAccountId(accountId);
        user.setAvatarUrl(mayunUser.getAvatarUrl());
        userService.insertOrUpdate(user);

        // 登陆成功 添加token
        response.addCookie(new Cookie("token",token));
        request.getSession().setAttribute("user",user);
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
